package org.boge.sharpdoc.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class CommonUtil {
    // 创建文件夹
    public static boolean createDir(String path) {
        File dir = new File(path);
        if (!dir.exists())
            return dir.mkdirs();
        return true;
    }

    // 删除文件夹及其下所有文件
    public static boolean deleteDir(File rootPath) {
        if (rootPath.isFile())
            return rootPath.delete();
        else {
            File[] files = rootPath.listFiles();
            if (files == null)
                return rootPath.delete();
            else {
                boolean res = true;
                for (File value : files)
                    res = res && deleteDir(value);
                return rootPath.delete() && res;
            }
        }
    }

    // 获取文件夹下所有文件
    public static List<File> getAllFile(File root) {
        List<File> res = new ArrayList<>();
        File[] files = root.listFiles();
        assert files != null;
        for (File item : files) {
            if (item.isDirectory())
                res.addAll(getAllFile(item));
            else
                res.add(item);
        }
        return res;
    }

    // 发送短信验证码
    public static void sendCheckCodeToPhone(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI7sdIfC6ei1yB", "q4RF6ntqEEWJB2BIvV5cuX4db5471A");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "sharpdoc文库");
        request.putQueryParameter("TemplateCode", "SMS_164278740");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
